package com.qianbao.qianbaobusiness.ui.borrow;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidbase.dialog.LoadingDialog;
import com.androidbase.dialog.MessageDialog;
import com.androidbase.utils.AndroidUtils;
import com.androidbase.utils.DeviceUuid;
import com.androidbase.utils.DisplayUtils;
import com.androidbase.utils.EncodeUtils;
import com.androidbase.utils.ImageUtils;
import com.androidbase.utils.RxUtils;
import com.androidbase.utils.StringUtils;
import com.androidbase.utils.ToastUtils;
import com.baseandroid.MyApplication;
import com.baseandroid.config.Api;
import com.baseandroid.config.Global;
import com.baseandroid.event.LocationResultEvent;
import com.baseandroid.gaode.GaoDeMap;
import com.baseandroid.mvp.BaseMvpFragment;
import com.baseandroid.retrofit.RxObserver;
import com.baseandroid.utils.FormatUtil;
import com.google.gson.Gson;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.MerchantInfo;
import com.qianbao.qianbaobusiness.ui.dialog.PicAndCamSelectDialog;
import com.qianbao.qianbaobusiness.ui.webview.LoanWebviewActivity;
import com.qianbao.qianbaobusiness.ui.webview.ScanLivenessUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import exocr.bankcard.CardRecoActivity;
import exocr.bankcard.EXBankCardInfo;
import exocr.exocrengine.EXIDCardResult;
import exocr.idcard.CaptureActivity;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;
import timber.log.Timber;

/*---fragment样式的招财贷---*/
public class BorrowFragment extends BaseMvpFragment<BorrowView, BorrowPresenter> implements BorrowView {

    private static final int PHOTO_REQUEST_CAMERA = 0x1001;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 0x1002;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 0x1003; // 图片进行裁剪
    private static final int MY_SCAN_REQUEST_CODE_BANK_FRONT = 0x1004;// OCR银行卡识别正面
    private static final int MY_SCAN_REQUEST_CODE_ID_FRONT = 0x1005;// OCR身份证识别正面
    private static final int MY_SCAN_REQUEST_CODE_ID_BACK = 0x1006;// OCR身份证识别反面
    private static final int MY_SCAN_REQUEST_CODE_LICENSE = 0x1007;// OCR营业执照识别
    private static final int CONTACTS_REQUEST_CODE_SINGLE = 0x1008;// 单一联系人选取
    private static final int contacts_REQUEST_CODE_MULTIPLE = 0x1009;// 多个联系人选取
    private static final int REQUEST_FINE_LOCATION = 0x1010;// 请求定位

    private static final String SUCCESS_CODE = "0000";
    private static final String SUCCESS_MSG = "成功";
    private static final String ID_ERROR_CODE = "1000";
    private static final String ID_ERROR_MSG = "身份证信息有误";
    private static final String ID_ERROR_CODE1 = "1001";
    private static final String ID_ERROR_MSG1 = "身份证姓名有误";
    private static final String ID_ERROR_CODE2 = "1002";
    private static final String ID_ERROR_MSG2 = "身份证性别有误";
    private static final String ID_ERROR_CODE3 = "1003";
    private static final String ID_ERROR_MSG3 = "身份证民族有误";
    private static final String ID_ERROR_CODE4 = "1004";
    private static final String ID_ERROR_MSG4 = "身份证生日有误";
    private static final String ID_ERROR_CODE5 = "1005";
    private static final String ID_ERROR_MSG5 = "身份证住址有误";
    private static final String ID_ERROR_CODE6 = "1006";
    private static final String ID_ERROR_MSG6 = "身份证卡号有误";
    private static final String ID_ERROR_CODE7 = "1007";
    private static final String ID_ERROR_MSG7 = "身份证正面照片有误";
    private static final String ID_ERROR_CODE8 = "1008";
    private static final String ID_ERROR_MSG8 = "身份证头像照片有误";
    private static final String ID_ERROR_CODE9 = "1009";
    private static final String ID_ERROR_MSG9 = "身份证签发机关有误";
    private static final String ID_ERROR_CODE10 = "1010";
    private static final String ID_ERROR_MSG10 = "身份证有效期有误";
    private static final String ID_ERROR_CODE11 = "1011";
    private static final String ID_ERROR_MSG11 = "身份证背面照片有误";

    private static final String BANK_ERROR_CODE = "2000";
    private static final String BANK_ERROR_MSG = "银行卡信息有误";
    private static final String BANK_ERROR_CODE1 = "2001";
    private static final String BANK_ERROR_MSG1 = "银行名称有误";
    private static final String BANK_ERROR_CODE2 = "2002";
    private static final String BANK_ERROR_MSG2 = "银行卡号有误";

    private static final String IMAGE_ERROR_CODE = "3000";
    private static final String IMAGE_ERROR_MSG = "照片信息有误";
    private static final String IMAGE_ERROR_CODE1 = "3001";
    private static final String IMAGE_ERROR_MSG1 = "照片信息有误";

    private static final String CONTACT_ERROR_CODE = "4000";
    private static final String CONTACT_ERROR_MSG = "联系人姓名有误";
    private static final String CONTACT_ERROR_CODE1 = "4001";
    private static final String CONTACT_ERROR_MSG1 = "联系人姓名有误";
    private static final String CONTACT_ERROR_CODE2 = "4002";
    private static final String CONTACT_ERROR_MSG2 = "联系人电话有误";

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_edit)
    TextView tv_edit;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.progress)
    TextView progress;
    @BindView(R.id.empty_layout)
    RelativeLayout empty_layout;
    @BindView(R.id.iv_bg_head)
    ImageView iv_bg_head;
    @BindView(R.id.iv_bg_location)
    ImageView iv_bg_location;
    @BindView(R.id.tv_notify)
    TextView tv_notify;
    @BindView(R.id.open_tips)
    TextView open_tips;

    protected String mUrl;
    protected String mInitTitle;

    private LoadingDialog mLoadingDialog;

    private int fromWhere = -1; // 方法入口fromWhere标识
    private String mCallBackMethodName;// 交互原生回调M站函数的方法名
    private String mCamImageName; // 拍照路径保存

    ScanLivenessUtil mScanLivenessUtil; //人脸识别处理

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_loan;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void setupView(View rootView) {
        if (Global.mbLocSuccess) {
            authLogin(Global.getUserInfoBean().getLoanAccessToken(), "loan_apply");
        } else {
            new RxPermissions(getActivity()).request(Manifest.permission.ACCESS_FINE_LOCATION)
                    .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                    .subscribe(new RxObserver<Boolean>() {
                        @Override
                        public void onNext(Boolean granted) {
                            if (granted) {
                                GaoDeMap.getInstance().startMap();
                            }
                        }
                    });
        }
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        mLoadingDialog = new LoadingDialog();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LocationResultEvent event) {
        if (event.isMbResult()) {
            authLogin(Global.getUserInfoBean().getLoanAccessToken(), "loan_apply");
        } else {
            updateEmptyView();
        }
    }

    private void updateEmptyView() {
        empty_layout.setVisibility(View.VISIBLE);
        webview.setVisibility(View.GONE);
        open_tips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new RxPermissions(getActivity()).request(Manifest.permission.ACCESS_FINE_LOCATION)
                        .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                        .subscribe(new RxObserver<Boolean>() {
                            @Override
                            public void onNext(Boolean granted) {
                                if (granted) {
                                    GaoDeMap.getInstance().startMap();
                                } else {
                                    jumpToSetting();
                                }
                            }
                        });
            }
        });
    }

    private void jumpToSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_FINE_LOCATION);
    }

    /**
     * 商户贷授权登录
     */
    public void authLogin(String token, String redirectURL) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("accessToken", token);
        param.put("sourceApp", "1");//1：商家app 2：销售crm app
        param.put("redirectURL", redirectURL);
        param.put("terminalNo", DeviceUuid.getDeviceId(getActivity()));
        param.put("longitude", Global.getMyLocation().getLongitude() + "");// 经度
        param.put("latitude", Global.getMyLocation().getLatitude() + "");// 纬度
        param.put("address", Global.getMyLocation().getAddress());
        param.put("shopProviceName", Global.getShopListInfo()
                .getLoanMerchantInfo().shopProviceName);
        param.put("shopCityName", Global.getShopListInfo()
                .getLoanMerchantInfo().shopCityName);
        param.put("registerNo", Global.getShopListInfo()
                .getLoanMerchantInfo().registerNo);//营业执照注册号
        param.put("businessStartDate", Global.getShopListInfo()
                .getLoanMerchantInfo().businessStartDate);//营业执照核发日期  8位日期格式yyyyMMdd
        param.put("businessEndDate", Global.getShopListInfo()
                .getLoanMerchantInfo().businessEndDate);//营业执照到期日期  8位日期格式yyyyMMdd
        param.put("legalPersonName", Global.getShopListInfo()
                .getLoanMerchantInfo().legalPersonName);//法人姓名
        param.put("legalCertNo", Global.getShopListInfo()
                .getLoanMerchantInfo().legalCertNo);//法人身份证号码
        param.put("legalMobile", Global.getShopListInfo()
                .getLoanMerchantInfo().legalMobile);//法人手机号码
        param.put("posAccountName", Global.getShopListInfo()
                .getLoanMerchantInfo().posAccountName);//结算账户姓名
        param.put("posAccountCertNo", Global.getShopListInfo()
                .getLoanMerchantInfo().posAccountCertNo);//结算账户身份证号码
        param.put("posAccountMobile", Global.getShopListInfo()
                .getLoanMerchantInfo().posAccountMobile);//结算账户手机号码
        param.put("managerName", Global.getShopListInfo()
                .getLoanMerchantInfo().managerName);//客户经理姓名
        param.put("managerMobile", Global.getShopListInfo()
                .getLoanMerchantInfo().managerMobile);//客户经理手机号
        MerchantInfo merchantInfo = Global.getShopListInfo().getLoanMerchantInfo();
        param.put("merchantNo", merchantInfo.merchantNo);//线上商户号
        param.put("posMerchantNo", merchantInfo.posMerchantNo);//pos商户号
        param.put("shopAddress", merchantInfo.shopAddress);//门店所在地址--总店分店字段有区别
        param.put("merchantName", merchantInfo.merchantName);//生活商户名称
        param.put("registerName", merchantInfo.registerName);//营业执照地址
        param.put("businessAddress", merchantInfo.businessAddress);//营业执照地址
        param.put("shopProviceName", merchantInfo.shopProviceName);//门店所在省名称
        param.put("shopCityName", merchantInfo.shopCityName);//门店所在市名称
        param.put("shopDistrictName", merchantInfo.shopDistrictName);//门店所在区名称
        param.put("merchantCategory", merchantInfo.merchantCategory);//门店分类 01：餐饮 02：亲子 03：商超
        param.put("realPersonName", Global.getShopListInfo()
                .getLoanMerchantInfo().realPersonName);//结算账户手机号码
        param.put("realCertNo", Global.getShopListInfo()
                .getLoanMerchantInfo().realCertNo);//结算账户手机号码
        param.put("realMobile", Global.getShopListInfo()
                .getLoanMerchantInfo().realMobile);//结算账户手机号码
        StringBuffer buffer = new StringBuffer();
        for (String key : param.keySet()) {
            if (!TextUtils.isEmpty(param.get(key))) {
                String value = EncodeUtils.urlEncode(param.get(key));
                if (TextUtils.isEmpty(value)) {
                    buffer.append(key + "=" + "&");
                } else {
                    buffer.append(key + "=" + value + "&");
                }
            } else {
                buffer.append(key + "=" + "&");
            }
        }
        mUrl = Api.sLoanApiUrl + "?" + buffer.toString();
        empty_layout.setVisibility(View.GONE);
        webview.setVisibility(View.VISIBLE);
        updateWebView();
    }

    private void updateWebView() {
        WebSettings webSettings = webview.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        //若加载的html里有JS在执行动画等操作，会造成资源浪费（CPU、电量）在onStop和onResume
        //里分别把 setJavaScriptEnabled()给设置成false和true即可
        webSettings.setJavaScriptEnabled(true);
        //设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        //webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面二个的前提。
        //webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        //webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        //设置图片加载
        webSettings.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        webSettings.setDatabaseEnabled(true);   //开启 database storage API 功能
        //String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        //webSettings.setAppCachePath(cacheDirPath); //设置  Application Caches 缓存目录
        webSettings.setAppCacheEnabled(false);//开启 Application Caches 功能
        //设置WebView是否使用其内置的变焦机制，该机制结合屏幕缩放控件使用，默认是false，不使用内置变焦机制。
        webSettings.setAllowContentAccess(false);
        //设置WebView是否保存表单数据，默认true，保存数据。
        webSettings.setSaveFormData(true);

        //缓存模式如下：
        //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
        if (AndroidUtils.isNetworkAvailable()) {
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
        }
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        webview.setWebChromeClient(mWebChromeClient);
        webview.setWebViewClient(mWebViewClient);

        String cookies = MyApplication.getAppComponent()
                .okhttpHelper()
                .getHttpCookieString(Api.sServerApiUrl);
        if (!TextUtils.isEmpty(cookies)) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.setCookie(mUrl, cookies);
            CookieSyncManager.getInstance().sync();
        }

        webview.loadUrl(mUrl);
    }


    //辅助WebView处理Javascript的对话框,网站图标,网站标题等
    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        private String mTitle;

        //获取Web页中的标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            this.mTitle = title;
            // tv_title.setText(mTitle);
        }

        //获得网页的加载进度并显示
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (getActivity() != null && !getActivity().isFinishing()) {
                if (newProgress < 99) {
                    // tv_title.setText(mTitle);
                } else {
                    // tv_title.setText(mTitle);
                }

                if (newProgress == 100) {
                    progress.setVisibility(View.GONE);
                } else {
                    progress.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams lp = progress.getLayoutParams();
                    lp.width = DisplayUtils.getWidth() * newProgress / 100;
                }
            }
        }

    };

    private WebViewClient mWebViewClient = new WebViewClient() {

        /**
         * 点击网页里面的链接还是在当前的webview里跳转
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Timber.e("------url = " + url);

            if (url.contains("newWebview")) {
                String newurl = url.replace("newWebview", "");
                Intent intent = new Intent(getActivity(), LoanWebviewActivity.class);
                intent.putExtra(LoanWebviewActivity.WEBVIEW_URL, newurl);
                startActivity(intent);
                return true;
            } else if (url.contains("app:")) {
                if (url.contains("app:requestCloseWebview")) {
                    // Not DealWith Not BackKey
                } else if (url.contains("app:requestOCR")) {
                    //app:requestOCR?callBack=success&type=01
                    //01---身份证正面02---身份证反面03---银行卡04---营业执照
                    url = url.replace(url.substring(0, url.lastIndexOf("?")), Api.sServerApiUrl + "test.html");
                    Uri uri = Uri.parse(url);
                    mCallBackMethodName = uri.getQueryParameter("callBack");
                    String type = uri.getQueryParameter("type");
                    if (TextUtils.equals(type, "01")) {
                        ToastUtils.showShortToast("OCR识别——身份证正面");
                        fromWhere = MY_SCAN_REQUEST_CODE_ID_FRONT;
                        startIDCardIdentify(true);
                    } else if (TextUtils.equals(type, "02")) {
                        ToastUtils.showShortToast("OCR识别——身份证反面");
                        fromWhere = MY_SCAN_REQUEST_CODE_ID_BACK;
                        startIDCardIdentify(false);
                    } else if (TextUtils.equals(type, "03")) {
                        ToastUtils.showShortToast("OCR识别——银行卡正面");
                        fromWhere = MY_SCAN_REQUEST_CODE_BANK_FRONT;
                        startBankCardIdentify();
                    } else if (TextUtils.equals(type, "04")) {
                        /* SDK未提供方法 */
                        ToastUtils.showShortToast("OCR识别——营业执照");
                        fromWhere = MY_SCAN_REQUEST_CODE_LICENSE;
                    }
                } else if (url.contains("app:requestPhoto")) {
                    //app:requestPhoto?callBack=success&type=01
                    //10---直接拍照01---从相册中选11---既可以拍照，又可以从相册中选择
                    url = url.replace(url.substring(0, url.lastIndexOf("?")), Api.sServerApiUrl + "test.html");
                    Uri uri = Uri.parse(url);
                    mCallBackMethodName = uri.getQueryParameter("callBack");
                    String type = uri.getQueryParameter("type");
                    if (TextUtils.equals(type, "01")) {
                        ToastUtils.showShortToast("从相册中选");
                        requestImage();
                    } else if (TextUtils.equals(type, "10")) {
                        ToastUtils.showShortToast("直接拍照");
                        requestCamera();
                    } else if (TextUtils.equals(type, "11")) {
                        ToastUtils.showShortToast("既可以拍照，又可以从相册中选择");
                        PicAndCamSelectDialog picAndCamSelectDialog = new PicAndCamSelectDialog(getActivity(), new PicAndCamSelectDialog.onItemSelectClick() {
                            @Override
                            public void onImageSelect() {
                                requestImage();
                            }

                            @Override
                            public void onCamaraSelect() {
                                requestCamera();
                            }
                        });
                        picAndCamSelectDialog.show();
                    }
                } else if (url.contains("app:requestContactList")) {
                    //app:requestContactList?callBack=success&type=1
                    //1---用户选择一条2---自动获取多条
                    url = url.replace(url.substring(0, url.lastIndexOf("?")), Api.sServerApiUrl + "test.html");
                    Uri uri = Uri.parse(url);
                    mCallBackMethodName = uri.getQueryParameter("callBack");
                    String type = uri.getQueryParameter("type");
                    if (TextUtils.equals(type, "1")) {
                        requestContactSingle();
                    } else if (TextUtils.equals(type, "2")) {
                        requestContactList(10);
                    }
                } else if (url.contains("app:requestFaceAuth")) {//人脸识别
                    url = url.replace(url.substring(0, url.lastIndexOf("?")), Api.sServerApiUrl + "test.html");
                    Uri uri = Uri.parse(url);
                    mCallBackMethodName = uri.getQueryParameter("callBack");
                    startFaceDetectScan();
                }
                return true;
            } else {
                if (!url.startsWith("http:") && !url.startsWith("https:")) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    return true;
                }
            }

            view.loadUrl(url);
            return true;
        }

        //开始载入页面调用的
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        //在页面加载结束时调用
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        //在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
            //handler.cancel(); 默认的处理方式，WebView变成空白页
            //接受证书
            sslErrorHandler.proceed();
            //handleMessage(Message msg); 其他处理
        }

        //加载页面的服务器出现错误时（如404）调用
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webview.setVisibility(View.GONE);
            //mEmptyView.setVisibility(View.VISIBLE);
            tv_title.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // tv_title.setText(mInitTitle);
                }
            }, 200);
        }

    };

    // 请求图片选择
    public void requestImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }

    // 请求拍照权限
    public void requestCamera() {
        new RxPermissions(getActivity()).request(Manifest.permission.CAMERA)
                .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                .subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean granted) {
                        if (granted) {
                            openCameraSuccess();
                        } else {
                            MessageDialog.goSettingPermission(getActivity(), "操作需要拍照权限，请进行权限设置允许拍照");
                        }
                    }
                });
    }

    private void openCameraSuccess() {
        // 判断是否挂载了SD卡
        mCamImageName = null;
        String savePath = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            savePath = getCameraPath();
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (TextUtils.isEmpty(savePath)) {
            ToastUtils.showShortToast("无法保存照片，请检查SD卡是否挂载");
            return;
        }

        mCamImageName = getSaveImageFullName();
        File out = new File(savePath, mCamImageName);

        /**
         * android N 系统适配
         */
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + "" + ".fileprovider", out);
        } else {
            uri = Uri.fromFile(out);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
    }

    public static String getCameraPath() {
        return Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/DCIM/Camera/";
    }

    public static String getSaveImageFullName() {
        return "qianbao_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".png";
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mScanLivenessUtil != null && !mScanLivenessUtil.handleActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
        }

        if (resultCode == AppCompatActivity.RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_GALLERY: {
                    if (data != null && data.getData() != null) {
                        Uri uri = data.getData();
                        mCamImageName = ImageUtils.getPath(getActivity(), uri);
                    }
                    sendBitmapFileUriName(mCallBackMethodName, mCamImageName);
                }
                break;

                case PHOTO_REQUEST_CAMERA: {
                    Uri localUri = Uri.fromFile(new File(getCameraPath() + mCamImageName));
                    Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                    getActivity().sendBroadcast(localIntent);
                    sendBitmapFileUriName(mCallBackMethodName, getCameraPath() + mCamImageName);
                }
                break;

                case MY_SCAN_REQUEST_CODE_BANK_FRONT:// OCR银行卡识别正面
                    if (data != null) {
                        getBankCardResult(data);
                    }
                    break;

                case MY_SCAN_REQUEST_CODE_ID_FRONT:// OCR身份证识别正面
                    if (data != null) {
                        getIDCardResult(data);
                    }
                    break;

                case MY_SCAN_REQUEST_CODE_ID_BACK:// OCR身份证识别反面
                    if (data != null) {
                        getIDCardResult(data);
                    }
                    break;

                case CONTACTS_REQUEST_CODE_SINGLE:// 获取通讯录，用户手动选择一条
                    if (data != null) {
                        getContactResult(data.getData(), 1);
                    }
                    break;

                case REQUEST_FINE_LOCATION:
                    new RxPermissions(getActivity()).request(Manifest.permission.ACCESS_FINE_LOCATION)
                            .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                            .subscribe(new RxObserver<Boolean>() {
                                @Override
                                public void onNext(Boolean granted) {
                                    if (granted) {
                                        GaoDeMap.getInstance().startMap();
                                    }
                                }
                            });
                    break;

                default:
                    break;
            }
        }
    }

    private void sendBitmapFileUriName(final String callBackMethodName, final String filepath) {
        if (mLoadingDialog != null && !mLoadingDialog.isVisible()) {
            mLoadingDialog.show(getActivity().getSupportFragmentManager(), "loadingdialog");
        }
        // 传入图片Base64数据
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                emitter.onNext(1);
                emitter.onComplete();
            }
        })
                .map(new Function<Integer, String>() {
                    @Override
                    public String apply(Integer integer) throws Exception {
                        Bitmap bitmaporgin = ImageUtils.decodeBitmap(filepath, 1280, 720);
                        Bitmap bitmaprotate = ImageUtils.rotateBitmap(bitmaporgin, ImageUtils
                                .getExifOrientation(filepath));
                        byte[] imagebyte = ImageUtils.bitmap2Bytes(ImageUtils.compressByQuality(bitmaprotate, (long) 500 * 1024), Bitmap.CompressFormat.JPEG);
                        String imagebytebase = new String(Base64.encode(imagebyte, Base64.NO_WRAP));
                        return imagebytebase.replaceAll("\r", "").replaceAll("\n", "");
                    }
                })
                .compose(RxUtils.<String>applySchedulersLifeCycle(getMvpView()))
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        if (mLoadingDialog != null) {
                            mLoadingDialog.dismissAllowingStateLoss();
                        }
                    }
                })
                .subscribe(new RxObserver<String>() {

                    @Override
                    public void onNext(String bytestring) {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("resultCode", SUCCESS_CODE);
                        map.put("resultMessage", SUCCESS_MSG);
                        map.put("image", bytestring);
                        String json = new Gson().toJson(map);
                        sendData(callBackMethodName, json);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("resultCode", IMAGE_ERROR_CODE);
                        map.put("resultMessage", IMAGE_ERROR_MSG);
                        map.put("image", "");
                        String json = new Gson().toJson(map);
                        sendData(callBackMethodName, json);
                    }
                });

    }

    /**
     * OCR——银行卡识别
     */
    public void startBankCardIdentify() {
        Intent scanIntent = new Intent(getContext(), CardRecoActivity.class);
        startActivityForResult(scanIntent, fromWhere);
    }

    /**
     * OCR——身份证识别 是否正面朝上，true是false否
     */
    public void startIDCardIdentify(boolean shouldFront) {
        Intent scanIntent = new Intent(getActivity(), CaptureActivity.class);
        scanIntent.putExtra("ShouldFront", shouldFront);
        startActivityForResult(scanIntent, fromWhere);
    }

    // 读取身份证识别及最终结果
    private void getIDCardResult(Intent data) {
        if (data != null) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                try {
                    EXIDCardResult idResult = extras.getParcelable(CaptureActivity.EXTRA_SCAN_RESULT);
                    int type = 1;
                    if (idResult != null) {
                        type = idResult.type;
                    } else {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("resultCode", ID_ERROR_CODE);
                        map.put("resultMessage", ID_ERROR_MSG);
                        String json = new Gson().toJson(map);
                        sendData(mCallBackMethodName, json);
                        return;
                    }
                    if (type == 1) {// 正面
                        //身份证前面扫描照片
                        Bitmap IDCardFrontFullImageBitmap = CaptureActivity.IDCardFrontFullImage;
                        //身份证头像扫描照片
                        Bitmap IDCardFaceImageBitmap = CaptureActivity.IDCardFaceImage;
                        //身份证姓名
                        final String name = idResult.name;
                        //身份证性别
                        final String sex = idResult.sex;
                        //身份证民族
                        final String nation = idResult.nation;
                        //身份证生日
                        final String birth = idResult.birth;
                        //身份证地址
                        final String address = idResult.address;
                        //身份证号
                        final String cardnum = idResult.cardnum;

                        if (TextUtils.isEmpty(name)) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("resultCode", ID_ERROR_CODE1);
                            map.put("resultMessage", ID_ERROR_MSG1);
                            String json = new Gson().toJson(map);
                            sendData(mCallBackMethodName, json);
                        } else if (TextUtils.isEmpty(sex)) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("resultCode", ID_ERROR_CODE2);
                            map.put("resultMessage", ID_ERROR_MSG2);
                            String json = new Gson().toJson(map);
                            sendData(mCallBackMethodName, json);
                        } else if (TextUtils.isEmpty(nation)) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("resultCode", ID_ERROR_CODE3);
                            map.put("resultMessage", ID_ERROR_MSG3);
                            String json = new Gson().toJson(map);
                            sendData(mCallBackMethodName, json);
                        } else if (TextUtils.isEmpty(birth)) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("resultCode", ID_ERROR_CODE4);
                            map.put("resultMessage", ID_ERROR_MSG4);
                            String json = new Gson().toJson(map);
                            sendData(mCallBackMethodName, json);
                        } else if (TextUtils.isEmpty(address)) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("resultCode", ID_ERROR_CODE5);
                            map.put("resultMessage", ID_ERROR_MSG5);
                            String json = new Gson().toJson(map);
                            sendData(mCallBackMethodName, json);
                        } else if (TextUtils.isEmpty(cardnum)) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("resultCode", ID_ERROR_CODE6);
                            map.put("resultMessage", ID_ERROR_MSG6);
                            String json = new Gson().toJson(map);
                            sendData(mCallBackMethodName, json);
                        } else {
                            if (IDCardFrontFullImageBitmap != null && IDCardFaceImageBitmap != null) {
                                Bitmap[] bitArray2 = new Bitmap[2];
                                bitArray2[0] = IDCardFrontFullImageBitmap;
                                bitArray2[1] = IDCardFaceImageBitmap;

                                if (mLoadingDialog != null && !mLoadingDialog.isVisible()) {
                                    mLoadingDialog.show(getActivity().getSupportFragmentManager(), "loadingdialog");
                                }
                                // 传入图片Base64数据
                                Observable.create(new ObservableOnSubscribe<Integer>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<Integer> emitter) throws
                                            Exception {
                                        emitter.onNext(1);
                                        emitter.onComplete();
                                    }
                                })
                                        .map(new Function<Integer, List<String>>() {
                                            @Override
                                            public List<String> apply(Integer integer) throws
                                                    Exception {
                                                List<String> imgebyteList = new ArrayList<String>();
                                                String imagebytebase = new String(Base64.encode(ImageUtils
                                                        .bitmap2Bytes(bitArray2[0], Bitmap.CompressFormat.JPEG), Base64.NO_WRAP));
                                                imgebyteList.add(imagebytebase.replaceAll("\r", "")
                                                        .replaceAll("\n", ""));
                                                imagebytebase = new String(Base64.encode(ImageUtils
                                                        .bitmap2Bytes(bitArray2[1], Bitmap.CompressFormat.JPEG), Base64.NO_WRAP));
                                                imgebyteList.add(imagebytebase.replaceAll("\r", "")
                                                        .replaceAll("\n", ""));
                                                return imgebyteList;
                                            }
                                        })
                                        .compose(RxUtils.<List<String>>applySchedulersLifeCycle(getMvpView()))
                                        .doFinally(new Action() {
                                            @Override
                                            public void run() throws Exception {
                                                if (mLoadingDialog != null) {
                                                    mLoadingDialog.dismissAllowingStateLoss();
                                                }
                                            }
                                        })
                                        .subscribe(new RxObserver<List<String>>() {

                                            @Override
                                            public void onNext(List<String> imgebyteList) {
                                                Map<String, String> map = new HashMap<String, String>();
                                                map.put("resultCode", SUCCESS_CODE);
                                                map.put("resultMessage", SUCCESS_MSG);
                                                map.put("name", name);// 姓名
                                                map.put("gender", sex);// 性别
                                                map.put("nation", nation);// 民族
                                                map.put("birthday", birth);// 出生日期
                                                map.put("address", address);// 地址
                                                map.put("certNo", cardnum);// 身份证号
                                                map.put("image", imgebyteList.get(0));// 身份证正面照片
                                                map.put("personImage", imgebyteList.get(1));// 身份证个人头像截图照片
                                                String json = new Gson().toJson(map);
                                                sendData(mCallBackMethodName, json);
                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                Map<String, String> map = new HashMap<String, String>();
                                                map.put("resultCode", ID_ERROR_CODE7);
                                                map.put("resultMessage", ID_ERROR_MSG7);
                                                String json = new Gson().toJson(map);
                                                sendData(mCallBackMethodName, json);
                                            }
                                        });
                            } else {
                                Map<String, String> map = new HashMap<String, String>();
                                map.put("resultCode", ID_ERROR_CODE7);
                                map.put("resultMessage", ID_ERROR_MSG7);
                                String json = new Gson().toJson(map);
                                sendData(mCallBackMethodName, json);
                            }
                        }
                    } else {// 反面
                        //身份证签发机关
                        final String office = idResult.office;
                        //身份证有效期限
                        final String validdate = idResult.validdate;
                        if (TextUtils.isEmpty(office)) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("resultCode", ID_ERROR_CODE9);
                            map.put("resultMessage", ID_ERROR_MSG9);
                            String json = new Gson().toJson(map);
                            sendData(mCallBackMethodName, json);
                        } else if (TextUtils.isEmpty(validdate)) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("resultCode", ID_ERROR_CODE10);
                            map.put("resultMessage", ID_ERROR_MSG10);
                            String json = new Gson().toJson(map);
                            sendData(mCallBackMethodName, json);
                        } else {
                            //身份证背面扫描照片
                            Bitmap IDCardBackFullImage = CaptureActivity.IDCardBackFullImage;
                            if (IDCardBackFullImage != null) {
                                Bitmap[] bitArray3 = new Bitmap[1];
                                bitArray3[0] = IDCardBackFullImage;
                                if (mLoadingDialog != null && !mLoadingDialog.isVisible()) {
                                    mLoadingDialog.show(getActivity().getSupportFragmentManager(), "loadingdialog");
                                }
                                // 传入图片Base64数据
                                Observable.create(new ObservableOnSubscribe<Integer>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<Integer> emitter) throws
                                            Exception {
                                        emitter.onNext(1);
                                        emitter.onComplete();
                                    }
                                })
                                        .map(new Function<Integer, String>() {
                                            @Override
                                            public String apply(Integer integer) throws
                                                    Exception {
                                                String imagebytebase = new String(Base64.encode(ImageUtils
                                                        .bitmap2Bytes(bitArray3[0], Bitmap.CompressFormat.JPEG), Base64.NO_WRAP));
                                                return imagebytebase.replaceAll("\r", "")
                                                        .replaceAll("\n", "");
                                            }
                                        })
                                        .compose(RxUtils.<String>applySchedulersLifeCycle(getMvpView()))
                                        .doFinally(new Action() {
                                            @Override
                                            public void run() throws Exception {
                                                if (mLoadingDialog != null) {
                                                    mLoadingDialog.dismissAllowingStateLoss();
                                                }
                                            }
                                        })
                                        .subscribe(new RxObserver<String>() {

                                            @Override
                                            public void onNext(String imgebytes) {
                                                Map<String, String> map = new HashMap<String, String>();
                                                map.put("resultCode", SUCCESS_CODE);
                                                map.put("resultMessage", SUCCESS_MSG);
                                                map.put("issuingUnit", office);// 签发机关
                                                // 处理有效期格式
                                                if (validdate.contains("-")) {
                                                    String[] vd = validdate.split("-");
                                                    if (vd.length > 0) {
                                                        map.put("startDate", FormatUtil.formatDate(vd[0]));// 有效开始日期1981-01-01
                                                        map.put("endDate", FormatUtil.formatDate(vd[1]));// 有效结束日期1981-01-01
                                                    }
                                                }
                                                map.put("image", imgebytes);// 身份证背面照片
                                                String json = new Gson().toJson(map);
                                                sendData(mCallBackMethodName, json);
                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                Map<String, String> map = new HashMap<String, String>();
                                                map.put("resultCode", ID_ERROR_CODE11);
                                                map.put("resultMessage", ID_ERROR_MSG11);
                                                String json = new Gson().toJson(map);
                                                sendData(mCallBackMethodName, json);
                                            }
                                        });
                            } else {
                                Map<String, String> map = new HashMap<String, String>();
                                map.put("resultCode", ID_ERROR_CODE11);
                                map.put("resultMessage", ID_ERROR_MSG11);
                                String json = new Gson().toJson(map);
                                sendData(mCallBackMethodName, json);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Map<String, String> map = new HashMap<String, String>();
                map.put("resultCode", ID_ERROR_CODE);
                map.put("resultMessage", ID_ERROR_MSG);
                String json = new Gson().toJson(map);
                sendData(mCallBackMethodName, json);
            }
        } else {
            Map<String, String> map = new HashMap<String, String>();
            map.put("resultCode", ID_ERROR_CODE);
            map.put("resultMessage", ID_ERROR_MSG);
            String json = new Gson().toJson(map);
            sendData(mCallBackMethodName, json);
        }

    }

    // 读取银行卡识别及最终结果并存储于结构体中
    private void getBankCardResult(Intent data) {
        if (data != null) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                EXBankCardInfo recoResult = extras.getParcelable(CardRecoActivity.BANK_RECO_RESULT); // 识别结果
                EXBankCardInfo finalResult = extras.getParcelable(CardRecoActivity.BANK_FINAL_RESULT); // 最终结果，可能被修改过
                boolean edited = extras.getBoolean(CardRecoActivity.BANK_EDITED); // 是否修改过
                // 银行名称
                String bankName = finalResult.strBankName;
                // 银行卡号
                String cardNo = finalResult.strNumbers;
                // 银行卡类型
                String cardType = finalResult.strCardType;
                // 获取卡号一栏的照片
                Bitmap BankCardImage = CardRecoActivity.markedCardImage;
                // 卡正面照片
                Bitmap BankFullImage = CardRecoActivity.cardFullImage;
                if (TextUtils.isEmpty(bankName)) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("resultCode", BANK_ERROR_CODE1);
                    map.put("resultMessage", BANK_ERROR_MSG1);
                    String json = new Gson().toJson(map);
                    sendData(mCallBackMethodName, json);
                } else if (TextUtils.isEmpty(cardNo)) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("resultCode", BANK_ERROR_CODE2);
                    map.put("resultMessage", BANK_ERROR_MSG2);
                    String json = new Gson().toJson(map);
                    sendData(mCallBackMethodName, json);
                } else {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("resultCode", SUCCESS_CODE);
                    map.put("resultMessage", SUCCESS_MSG);
                    map.put("bankName", bankName);// 银行名称
                    map.put("cardNo", cardNo);// 银行卡号
                    map.put("cardType", cardType);// 银行卡类型
                    String json = new Gson().toJson(map);
                    sendData(mCallBackMethodName, json);
                }
            } else {
                Map<String, String> map = new HashMap<String, String>();
                map.put("resultCode", BANK_ERROR_CODE);
                map.put("resultMessage", BANK_ERROR_MSG);
                String json = new Gson().toJson(map);
                sendData(mCallBackMethodName, json);
            }
        } else {
            Map<String, String> map = new HashMap<String, String>();
            map.put("resultCode", BANK_ERROR_CODE);
            map.put("resultMessage", BANK_ERROR_MSG);
            String json = new Gson().toJson(map);
            sendData(mCallBackMethodName, json);
        }
    }

    /**
     * 开始人脸识别
     */
    public void startFaceDetectScan() {
        mScanLivenessUtil = new ScanLivenessUtil(getActivity(), new ScanLivenessUtil.MyScanListener() {

            @Override
            public void onScanSucceed(String imgBase64, String imgFileStr) {
                Map<String, String> map = new HashMap<>();
                map.put("resultCode", "0000");
                map.put("resultMessage", "成功");
                map.put("faceImage", imgBase64);// 照片base64
                map.put("binaryFile", imgFileStr);// 二进制流文件string
                String json = new Gson().toJson(map);
                sendData(mCallBackMethodName, json);
            }

            @Override
            public void onScanFail(int errorCode, String errorMessage) {
                Map<String, Object> map = new HashMap<>();
                map.put("resultCode", errorCode);
                map.put("resultMessage", errorMessage);
                String json = new Gson().toJson(map);
                sendData(mCallBackMethodName, json);
            }
        });
        mScanLivenessUtil.applyScanLiveness();
    }

    private void requestContactSingle() {
        new RxPermissions(getActivity()).request(Manifest.permission.READ_CONTACTS)
                .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                .subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean granted) {
                        if (granted) {
                            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                            startActivityForResult(intent, CONTACTS_REQUEST_CODE_SINGLE);
                        } else {
                            MessageDialog.goSettingPermission(getActivity(), "操作需要通讯录权限，请进行权限设置允许拍照");
                        }
                    }
                });
    }

    private void requestContactList(final int count) {
        new RxPermissions(getActivity()).request(Manifest.permission.READ_CONTACTS)
                .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                .subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean granted) {
                        if (granted) {
                            getContactResult(ContactsContract.Contacts.CONTENT_URI, count);
                        } else {
                            MessageDialog.goSettingPermission(getActivity(), "操作需要通讯录权限，请进行权限设置允许拍照");
                        }
                    }
                });
    }

    private void getContactResult(Uri uri, int count) {
        Timber.e("uri = " + uri.toString());
        String username = null;
        String usernumber = null;
        if (uri == null) {
            return;
        }
        ContentResolver reContentResolverol = getActivity().getContentResolver();
        Cursor cursor = reContentResolverol.query(uri, null, null, null, null);
        if (cursor == null) {
            ToastUtils.showShortToast("获取联系人失败，请查看系统设置");
            return;
        }
        if (cursor.moveToFirst()) {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            // 取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            username = cursor.getString(nameFieldColumnIndex);
            String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            // 取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            if (hasPhone.equalsIgnoreCase("1")) {
                hasPhone = "true";
            } else {
                hasPhone = "false";
            }
            if (Boolean.parseBoolean(hasPhone)) {
                Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
                while (phone.moveToNext()) {
                    phone.moveToFirst();
                    usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Map<String, String> map1 = new HashMap<String, String>();
                    map1.put("contactName", username);// 联系人姓名
                    map1.put("phoneNum", usernumber.trim());// 联系人手机号
                    list.add(map1);
                    if (list.size() == count) {
                        break;
                    }
                }
                if (StringUtils.isEmpty(usernumber)) {
                    ToastUtils.showShortToast("获取号码为空");
                }
                phone.close();
            }

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("resultCode", SUCCESS_CODE);
            map.put("resultMessage", SUCCESS_MSG);
            map.put("list", list);
            String json = new Gson().toJson(map);
            Timber.e("getContactResult = " + json);
            sendData(mCallBackMethodName, json);
            cursor.close();
        }
    }

    private void sendData(String callBackMethodName, String json) {
        if (Build.VERSION.SDK_INT >= 19) {// 4.4以上支持
            webview.evaluateJavascript(callBackMethodName + "('" + json + "')", null);
        } else {
            webview.loadUrl("javascript:" + callBackMethodName + "('" + json + "')");
        }
    }

    @Override
    public void onDestroy() {
        if (webview != null) {
            webview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);

            //这个api仅仅清除自动完成填充的表单数据，并不会清除WebView存储到本地的数据
            webview.clearFormData();

            //清除当前webview访问的历史记录
            //只会webview访问历史记录里的所有记录除了当前访问记录
            webview.clearHistory();

            //清除网页访问留下的缓存
            //由于内核缓存是全局的因此这个方法不仅仅针对webview而是针对整个应用程序.
            webview.clearCache(true);

            ((ViewGroup) webview.getParent()).removeView(webview);
            webview.destroy();
            webview = null;
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
